
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <linux/input.h>
#include "font.h"
#include "lv_draw.h"
#include "touch.h"
#include <time.h>
#include <sys/time.h>
extern volatile int run_chinese;

#define MAX_USERS 100
#define MAX_USERNAME_LEN 50
#define MAX_PASSWORD_LEN 50

#define STATE_HOME 0
#define STATE_LOGIN 1
#define STATE_REGISTER 2
volatile int ui_state = STATE_HOME;

#define INPUT_MODE_NONE 0
#define INPUT_MODE_USERNAME 1
#define INPUT_MODE_PASSWORD 2
volatile int input_mode = INPUT_MODE_NONE;
volatile int input_changed = 0;
char username_input[MAX_USERNAME_LEN] = {0};
char password_input[MAX_PASSWORD_LEN] = {0};
int input_pos = 0;
volatile int submit_clicked = 0;
volatile int login_success = 0;

typedef struct
{
    char username[MAX_USERNAME_LEN];
    char password[MAX_PASSWORD_LEN];
} User;

void handle_touch_input(int x, int y)
{
    if (ui_state == STATE_HOME)
    {
        if (y >= 300 && y <= 350 && x >= 300 && x <= 500)
        {
            ui_state = STATE_LOGIN;
            input_mode = INPUT_MODE_NONE;
            memset(username_input, 0, MAX_USERNAME_LEN);
            memset(password_input, 0, MAX_PASSWORD_LEN);
            input_pos = 0;
            return;
        }

        if (y >= 200 && y <= 250 && x >= 300 && x <= 500)
        {
            ui_state = STATE_REGISTER;
            input_mode = INPUT_MODE_NONE;
            memset(username_input, 0, MAX_USERNAME_LEN);
            memset(password_input, 0, MAX_PASSWORD_LEN);
            input_pos = 0;
            return;
        }
    }

    if (ui_state == STATE_LOGIN || ui_state == STATE_REGISTER)
    {
        if (y >= 400 && y <= 450 && x >= 600 && x <= 750)
        {
            ui_state = STATE_HOME;
            input_mode = INPUT_MODE_NONE;
            memset(username_input, 0, MAX_USERNAME_LEN);
            memset(password_input, 0, MAX_PASSWORD_LEN);
            input_pos = 0;
            return;
        }

        if (y >= 100 && y <= 140 && x >= 225 && x <= 575)
        {
            input_mode = INPUT_MODE_USERNAME;
            input_pos = strlen(username_input);
            input_changed = 1;
            return;
        }

        if (y >= 170 && y <= 210 && x >= 225 && x <= 575)
        {
            input_mode = INPUT_MODE_PASSWORD;
            input_pos = strlen(password_input);
            input_changed = 1;
            return;
        }

        if (y >= 250 && y <= 440 && x >= 250 && x <= 550)
        {
            int col = (x - 250) / 100;
            int row = (y - 250) / 50;

            if (col >= 0 && col < 3 && row >= 0 && row <= 3)
            {
                char key = '0';

                if (row < 3)
                {
                    key = '1' + row * 3 + col;
                }
                else if (row == 3)
                {
                    if (col == 0)
                        key = 'D';
                    if (col == 1)
                        key = '0';
                    if (col == 2)
                        key = 'E';
                }

                if (key == 'D' && input_pos > 0)
                {
                    input_pos--;
                    if (input_mode == INPUT_MODE_USERNAME)
                    {
                        username_input[input_pos] = '\0';
                    }
                    else
                    {
                        password_input[input_pos] = '\0';
                    }
                    input_changed = 1;
                }
                else if (key >= '0' && key <= '9' && input_pos < MAX_USERNAME_LEN - 1)
                {
                    if (input_mode == INPUT_MODE_USERNAME)
                    {
                        username_input[input_pos] = key;
                    }
                    else
                    {
                        password_input[input_pos] = key;
                    }
                    input_pos++;
                    input_changed = 1;
                }
                else if (key == 'E')
                {
                    input_mode = INPUT_MODE_NONE;
                    submit_clicked = 1;
                }
            }
            return;
        }
    }
}

void *touch_thread(void *arg)
{
    int touch_fd = open("/dev/input/event0", O_RDONLY);
    if (touch_fd == -1)
    {
        perror("open touch device failed");
        return NULL;
    }

    struct input_event event;
    int x0 = -1, y0 = -1;
    int x = 0, y = 0;

    while (!login_success)
    {
        if (read(touch_fd, &event, sizeof(event)) != sizeof(event))
        {
            perror("read touch event failed");
            continue;
        }

        if (event.type == EV_ABS)
        {
            if (event.code == ABS_X)
            {
                x = event.value * 800 / 1024;
            }
            else if (event.code == ABS_Y)
            {
                y = event.value * 480 / 600;
            }
        }

        if (event.type == EV_KEY && event.code == BTN_TOUCH)
        {
            if (event.value == 1)
            {
                x0 = x;
                y0 = y;
            }
            else if (event.value == 0)
            {
                if (x0 != -1 && y0 != -1)
                {
                    handle_touch_input(x0, y0);
                    x0 = -1;
                    y0 = -1;
                }
            }
        }
    }

    close(touch_fd);
    return NULL;
}

void show_home_screen()
{
    lv_clear_fill(RGB(255, 255, 255));
    lv_draw_string_bmp("智慧小区登录系统", 250, 50, RGB(0, 0, 0), 32);
    lv_fill_clean_bmp(300, 200, 200, 50, RGB(0, 200, 255));
    lv_draw_string_bmp("注册", 370, 215, RGB(0, 0, 0), 28);
    lv_fill_clean_bmp(300, 300, 200, 50, RGB(0, 255, 0));
    lv_draw_string_bmp("登录", 370, 315, RGB(0, 0, 0), 28);
}

void show_input_screen()
{
    lv_clear_fill(RGB(255, 255, 255));
    lv_draw_string_bmp("智慧小区登录系统", 260, 20, RGB(0, 0, 0), 32);
    lv_draw_string_bmp("用户名:", 175, 100, RGB(0, 0, 0), 24);
    lv_fill_clean_bmp(225, 100, 350, 40, RGB(240, 240, 240));
    lv_draw_string_bmp("密码:", 175, 170, RGB(0, 0, 0), 24);
    lv_fill_clean_bmp(225, 170, 350, 40, RGB(240, 240, 240));
    lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
    lv_fill_clean_bmp(225, 210, 350, 20, RGB(255, 255, 255));

    const char *keys[3][3] = {
        {"1", "2", "3"},
        {"4", "5", "6"},
        {"7", "8", "9"}};

    const char *bottom_keys[3] = {"删除", "0", "确认"};

    for (int row = 0; row < 3; row++)
    {
        for (int col = 0; col < 3; col++)
        {
            int x = 250 + col * 100;
            int y = 250 + row * 50;
            lv_fill_clean_bmp(x, y, 90, 40, RGB(200, 200, 200));
            lv_draw_string_bmp(keys[row][col], x + 35, y + 10, RGB(0, 0, 0), 24);
        }
    }

    for (int col = 0; col < 3; col++)
    {
        int x = 250 + col * 100;
        int y = 400;
        lv_fill_clean_bmp(x, y, 90, 40, RGB(200, 200, 200));
        lv_draw_string_bmp(bottom_keys[col], x + 15, y + 10, RGB(0, 0, 0), 24);
    }

    lv_fill_clean_bmp(600, 400, 150, 50, RGB(200, 200, 200));
    lv_draw_string_bmp("返回", 650, 415, RGB(0, 0, 0), 28);
}

void update_input_fields()
{
    lv_fill_clean_bmp(235, 105, 340, 24, RGB(240, 240, 240));
    if (strlen(username_input))
    {
        lv_draw_string_bmp(username_input, 235, 105, RGB(0, 0, 0), 24);
    }
    else
    {
        lv_draw_string_bmp("点击输入用户名", 235, 105, RGB(180, 180, 180), 24);
    }

    lv_fill_clean_bmp(235, 175, 340, 24, RGB(240, 240, 240));
    if (strlen(password_input))
    {
        char hidden_pass[MAX_PASSWORD_LEN] = {0};
        for (int i = 0; i < strlen(password_input); i++)
        {
            hidden_pass[i] = '*';
        }
        lv_draw_string_bmp(hidden_pass, 235, 175, RGB(0, 0, 0), 24);
    }
    else
    {
        lv_draw_string_bmp("点击输入密码", 235, 175, RGB(180, 180, 180), 24);
    }

    lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
    lv_fill_clean_bmp(225, 210, 350, 20, RGB(255, 255, 255));

    // 修改点1：区分登录/注册状态的提示文字
    if (input_mode == INPUT_MODE_USERNAME)
    {
        const char *prefix = (ui_state == STATE_LOGIN) ? "登录" : "注册";
        char prompt[50];
        snprintf(prompt, sizeof(prompt), "已选择%s用户名输入框", prefix);
        lv_draw_string_bmp(prompt, 235, 140, RGB(255, 0, 0), 20);
    }
    else if (input_mode == INPUT_MODE_PASSWORD)
    {
        const char *prefix = (ui_state == STATE_LOGIN) ? "登录" : "注册";
        char prompt[50];
        snprintf(prompt, sizeof(prompt), "已选择%s密码输入框", prefix);
        lv_draw_string_bmp(prompt, 235, 210, RGB(255, 0, 0), 20);
    }
}

int loadUsers(User users[])
{
    FILE *file = fopen("user.txt", "r");
    if (!file)
        return 0;

    int count = 0;
    while (fscanf(file, "%s %s", users[count].username, users[count].password) == 2)
    {
        count++;
        if (count >= MAX_USERS)
            break;
    }
    fclose(file);
    return count;
}

void saveUser(User newUser)
{
    FILE *file = fopen("user.txt", "a");
    if (!file)
    {
        printf("无法打开用户文件!\n");
        return;
    }
    fprintf(file, "%s %s\n", newUser.username, newUser.password);
    fclose(file);
}

void registerUser()
{
    User users[MAX_USERS];
    int userCount = loadUsers(users);

    for (int i = 0; i < userCount; i++)
    {
        if (strcmp(users[i].username, username_input) == 0)
        {
            lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
            lv_draw_string_bmp("用户名已存在!", 235, 140, RGB(255, 0, 0), 20);
            sleep(2);
            lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
            input_changed = 1;
            return;
        }
    }

    User newUser;
    strcpy(newUser.username, username_input);
    strcpy(newUser.password, password_input);
    saveUser(newUser);

    lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
    lv_draw_string_bmp("注册成功!", 235, 140, RGB(0, 255, 0), 20);
    sleep(2);

    memset(username_input, 0, MAX_USERNAME_LEN);
    memset(password_input, 0, MAX_PASSWORD_LEN);
    input_pos = 0;
    ui_state = STATE_HOME;
}

int loginUser()
{
    User users[MAX_USERS];
    int userCount = loadUsers(users);

    for (int i = 0; i < userCount; i++)
    {
        if (strcmp(users[i].username, username_input) == 0)
        {
            if (strcmp(users[i].password, password_input) == 0)
            {
                lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
                lv_draw_string_bmp("登录成功!", 235, 140, RGB(0, 255, 0), 20);
                sleep(2);
                return 1;
            }
            else
            {
                lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
                lv_draw_string_bmp("密码错误!", 235, 140, RGB(255, 0, 0), 20);
                sleep(2);
                lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
                input_changed = 1;
                return 0;
            }
        }
    }

    lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
    lv_draw_string_bmp("用户不存在!", 235, 140, RGB(255, 0, 0), 20);
    sleep(2);
    lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
    input_changed = 1;
    return 0;
}

int login()
{
    pthread_t touch_tid;

    if (pthread_create(&touch_tid, NULL, touch_thread, NULL) != 0)
    {
        perror("创建触摸线程失败");
        return 0;
    }

    ui_state = STATE_HOME;
    show_home_screen();

    int last_ui_state = -1;

    while (!login_success)
    {
        if (last_ui_state != ui_state)
        {
            last_ui_state = ui_state;

            if (ui_state == STATE_HOME)
            {
                show_home_screen();
            }
            else
            {
                show_input_screen();
                update_input_fields();
            }
        }

        if (input_changed)
        {
            update_input_fields();
            input_changed = 0;
        }

        if (submit_clicked)
        {
            submit_clicked = 0;

            if (strlen(username_input) > 0 && strlen(password_input) > 0)
            {
                if (ui_state == STATE_LOGIN)
                {
                    login_success = loginUser();
                }
                else
                {
                    registerUser();
                }

                last_ui_state = -1;
                input_changed = 1;
            }
            else
            {
                lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
                lv_draw_string_bmp("用户名或密码不能为空", 235, 140, RGB(255, 0, 0), 20);
                sleep(2);
                lv_fill_clean_bmp(225, 140, 350, 20, RGB(255, 255, 255));
                input_changed = 1;
            }
        }

        usleep(100000);
    }

    pthread_cancel(touch_tid);
    pthread_join(touch_tid, NULL);
    lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
    run_chinese = 1;
    return login_success;
}